<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Wechat\UserDrawInviteController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PhpParser\Node\Stmt\Else_;

/*活动model*/

class AnswerActivity extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity';

    protected $guarded = []; //使用模型  update 更新时，允许被全部更新，若不写，则会报错 或 没任何数据变化





    /**
     * 更新浏览量
     *
     * @param act_id 活动id
     * @param number 多少次更新一次
     * @param second 大于秒更新一次（取决于后一次请求事件）
     */
    public function updateBrowseNumber($act_id, $number = 100, $second = 300)
    {
        if ($number == 1) {
            return $this->where('act_id', $act_id)->increment('browse_num', 1);
        }

        $key = $act_id . 'answer_activity_browse_number';
        $res = Cache::pull($key); //从缓存中获取缓存项然后删除，使用 pull 方法，如果缓存项不存在的话返回 null
        $data = [];
        if (empty($res)) {
            $data['number'] = 1;
            $data['create_time'] = time();
            Cache::put($key, $data, 3600 * 24);
        } else {
            //数据大于50或者时间超过5分钟，则更新一次数据
            if ($res['number'] >= $number || time() - $res['create_time'] >= $second) {
                return $this->where('id', $act_id)->increment('browse_num', $res['number'] + 1);
            } else {
                $data['number'] = $res['number'] + 1;
                $data['create_time'] = $res['create_time'];
                Cache::put($key, $data, 3600 * 24);
            }
        }
        return true;
    }
    /**
     * 获取活动类型
     * $node 活动类型    1 独立活动  2 单位联盟   3 区域联盟
     */
    public function getNodeName($node = null)
    {
        $data = ['1' => '独立活动', '单位联盟', '区域联盟'];
        if ($node) {
            return $data[$node];
        }
        return $data;
    }

    /**
     * 获取答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     * $pattern
     */
    public function getPatternName($pattern = null)
    {
        $data = ['1' => '挑战模式', '成绩模式', '阶段模式'];
        if ($pattern) {
            return $data[$pattern];
        }
        return $data;
    }

    /**
     * 获奖情况  1 排名  2 抽奖
     * $prize_form
     */
    public function getPrizeFormName($prize_form = null)
    {
        $data = ['1' => '排名', '抽奖'];
        if ($prize_form) {
            return $data[$prize_form];
        }
        return $data;
    }


    /**
     * 获取活动列表
     * @param field int 需要获取的字段 数组形式
     * @param page int 页码
     * @param limit int 分页大小
     * @param is_play string 是否发布   1 已发布  2 未发布
     * @param keywords string 搜索关键词
     * @param start_time datetime 活动开始时间    数据格式  年月日
     * @param end_time datetime 活动结束时间
     * @param node int 活动类型    1 独立活动  2 单位联盟   3 区域联盟
     * @param pattern int 答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     * @param prize_form int 获奖情况  1 排名  2 抽奖
     *
     * @param create_start_time datetime 活动创建开始时间   数据格式 年月日时分秒
     * @param create_end_time datetime 活动创建结束时间
     */
    public function lists($field = [], $keywords = null, $is_play = null, $node = null, $pattern = null, $prize_form = null, $start_time = null, $end_time = null, $create_start_time = null, $create_end_time = null, $page = 1, $limit = 10)
    {
        if (empty($field)) {
            $field = [
                'id',
                'title',
                'img',
                'node',
                'pattern',
                'prize_form',
                'real_info',
                'is_need_unit',
                'total_floor',
                'number',
                'answer_number',
                'is_loop',
                'share_number',
                'answer_time',
                'rule_type',
                'rule',
                'start_time',
                'end_time',
                'end_time',
                'answer_start_time',
                'answer_end_time',
                'lottery_start_time',
                'lottery_end_time',
                'invite_code',
                'is_play',
                'create_time',
                'manage_id',
                'qr_url'
            ];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($is_play, $node, $pattern, $prize_form, $start_time, $end_time, $create_start_time, $create_end_time) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
                if ($node) {
                    $query->where('node', $node);
                }
                if ($pattern) {
                    $query->where('pattern', $pattern);
                }
                if ($prize_form) {
                    $query->where('prize_form', $prize_form);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('start_time', [$start_time, $end_time]);
                }
                if ($create_start_time && $create_end_time) {
                    $query->whereBetween('create_time', [$create_start_time, $create_end_time]);
                }
            })->where('is_del', 1)
            ->orderByDesc('start_time')
            ->paginate($limit)
            ->toArray();

        $controllerObj = new Controller();
        $res = $controllerObj->disPageData($res);

        return $res;
    }

    /**
     * 获取活动详情
     * @param $id
     */
    public function detail($id, $field = [], $is_play = 1)
    {
        if (empty($field)) {
            $field = [
                'id',
                'title',
                'node',
                'number',
                'answer_number',
                'rule_type',
                'rule',
                'share_number',
                'answer_start_time',
                'answer_end_time',
                'start_time',
                'end_time',
                'lottery_start_time',
                'lottery_end_time',
                'answer_rule',
                'answer_time',
                'total_floor',
                'is_loop',
                'pattern',
                'prize_form',
                'invite_code',
                'qr_url',
                'share_title',
                'real_info',
                'is_show_address',
                'technical_support',
                'is_reset_data'
            ];
        }
        $act_info = $this->select($field)
            ->where('id', $id)
            ->where('is_del', 1)
            ->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->first();

        return $act_info;
    }
    /**
     * 获取单位详情
     * @param qr_code int 二维码code信息
     */
    public function getDetailByQrCode($qr_code, $field = [], $is_play = 1)
    {
        if (empty($field)) {
            $field = ['id', 'title', 'node', 'number', 'answer_number', 'rule_type', 'rule', 'share_number', 'answer_start_time', 'answer_end_time', 'start_time', 'end_time', 'lottery_start_time', 'lottery_end_time', 'answer_rule', 'answer_time', 'total_floor', 'is_loop', 'pattern', 'prize_form', 'invite_code', 'qr_url', 'share_title'];
        }
        $act_info = $this->select($field)
            ->where('qr_code', $qr_code)
            ->where('is_del', 1)
            ->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->first();

        return $act_info;
    }

    /**
     * 用户活动报名填写信息
     */
    public static function getAnswerActivityApplyParam()
    {
        return [
            ['id' => 1, 'field' => 'username', 'value' => '姓名'],
            ['id' => 2, 'field' => 'tel', 'value' => '电话号码'],
            ['id' => 3, 'field' => 'id_card', 'value' => '身份证号码'],
            ['id' => 4, 'field' => 'reader_id', 'value' => '读者证号'],
        ];
    }


    /**
     * 活动列表状态
     * status 活动状态 1 活动未开始 2.答题未开始 3.进行中 4.答题已结束  5 活动已结束   20.即将开始
     **/
    public function getActListStatus($act_data)
    {
        $now_date = date('Y-m-d H:i:s');
        if ($act_data['start_time'] > $now_date) {
            $status = 1;
        } elseif ($act_data['end_time'] < $now_date) {
            $status = 5;
        } elseif ($act_data['start_time'] < $now_date && $act_data['answer_start_time'] > $now_date) {
            $status = 2;
        } elseif ($act_data['answer_start_time'] < $now_date && $act_data['answer_end_time'] > $now_date) {
            $status = 3;
        } else {
            $status = 4;
        }

        //计算即将开始
        if ($status == 1) {
            if ($act_data['start_time'] > date('Y-m-d H:i:s', strtotime("-10 day"))) {
                $status = 20;
            }
        }
        return $status;
    }
    /**
     * 判断是否还可以答题
     */
    public function isCanAnswer($act_info, $user_guid = null)
    {
        $status = $this->getActListStatus($act_info);

        //判断是否输入邀请码，输入邀请码就跳过此验证
        if ($user_guid && ($status == 1 || $status == 2)) {
            $userDrawInviteObj = new UserDrawInviteController();
            $checkInviteCode = $userDrawInviteObj->checkInviteCode(1, $user_guid, $act_info['id'], $act_info['invite_code']);

            if ($checkInviteCode === true) {
                return true;
            }
        }

        switch ($status) {
            case 1:
            case 20:
                return '活动未开始';
                break;
            case 2:
                return '答题未开始';
                break;
            case 4:
                return '答题已结束';
                break;
            case 5:
                return '活动已结束';
                break;
        }

        return true;
    }

    /**
     * 判断是否还可以抽奖
     */
    public function isCanDraw($act_info, $user_guid = null)
    {
        if ($act_info['lottery_start_time'] > date('Y-m-d H:i:s') || $act_info['lottery_end_time'] < date('Y-m-d H:i:s')) {
            //判断是否输入邀请码，输入邀请码就跳过此验证
            if ($user_guid) {
                $userDrawInviteObj = new UserDrawInviteController();
                $checkInviteCode = $userDrawInviteObj->checkInviteCode(1, $user_guid, $act_info['id'], $act_info['invite_code']);
                if ($checkInviteCode === true) {
                    return true;
                }
            }
            return '不在抽奖时间段内';
        }
        return true;
    }



    /**
     * 判断是否是最后一天,提示不同的话
     * $answer_end_time  答题结束时间
     */
    public function isEndTime($answer_end_time)
    {
        if (date('Y-m-d', strtotime($answer_end_time)) == date('Y-m-d')) {
            return '感谢您的参与';
        }

        return '请明日再来！';
    }


    /**
     * @param array $real_info
     * @param $username
     * @param $id_card
     * @param $tel
     * @param $reader_id
     * @param $img
     * @return array
     */
    public function checkApplyParam(array $real_info, $username, $id_card, $tel, $reader_id, $img)
    {
        $where = [];
        foreach ($real_info as $key => $val) {
            if ($val == 1) {
                if (empty($username)) {
                    throw new Exception('用户名不能为空');
                } else {
                    $where['username'] = $username;
                }
            } elseif ($val == 2) {
                if (empty($id_card)) {
                    throw new Exception('用户名不能为空');
                } else {
                    $where['id_card'] = $id_card;
                }
            } elseif ($val == 3) {
                if (empty($tel)) {
                    throw new Exception('电话号码不能为空');
                } else {
                    $where['tel'] = $tel;
                }
            } elseif ($val == 4) {
                if (empty($reader_id)) {
                    throw new Exception('读者证不能为空');
                } else {
                    $where['reader_id'] = $reader_id;
                }
            } elseif ($val == 5) {
                if (empty($img)) {
                    throw new Exception('头像不能为空');
                } else {
                    $where['img'] = $img;
                }
            }
        }
        return $where;
    }

    /**
     * 是否满足发布的条件
     * @param act_id 活动id
     */
    public function isCanPlay($act_id)
    {
        $act_info = $this->where('id', $act_id)->first();
        //判断是否配置颜色资源
        $answerActivityResource = new AnswerActivityResource();
        $color_info = $answerActivityResource->detail($act_id);
        if (empty($color_info) || empty($color_info['theme_color'])) {
            return '活动主题颜色未设置，请先设置';
        } elseif (empty($color_info['resource_path'])) {
            return '活动图片资源未设置，请先设置';
        }
        //判断是否配置问题选项
        $problem_info = AnswerActivityProblem::isHaveProblem($act_id);
        if ($problem_info !== true) {
            return $problem_info;
        }
        //活动类型    1 独立活动  2 单位联盟   3 区域联盟
        if ($act_info['node'] == 2) {
            //判断是否配置单位
            $unit_info = AnswerActivityUnit::isHaveUnit($act_id);
            if ($unit_info !== true) {
                return $unit_info;
            }
        } elseif ($act_info['node'] == 3) {
            //判断是否配置区域
            $area_info = AnswerActivityArea::isHaveArea($act_id);
            if ($area_info !== true) {
                return $area_info;
            }
            //判断是否配置单位
            $unit_info = AnswerActivityUnit::isHaveUnit($act_id);
            if ($unit_info !== true) {
                return $unit_info;
            }
        }

        if ($act_info['prize_form'] == 2) {
            //判断是否配置奖品
            $gift_info = AnswerActivityGift::isHaveGift($act_id);
            if ($gift_info !== true) {
                return $gift_info;
            }
            //判断是否配置奖品
            $gift_public_info = AnswerActivityGiftPublic::isHaveGiftPublic($act_id);
            if ($gift_public_info !== true) {
                return $gift_public_info;
            }
        }
        return true;
    }


    /**
     * 获取操作记录model
     * @param pattern
     */
    public function getAnswerTotalRecordModel($pattern)
    {
        switch ($pattern) {
            case 1:
                $model = new AnswerActivityUserAnswerTotalNumber();
                break;
            case 2:
                $model = new AnswerActivityUserCorrectTotalNumber();
                break;
            case 3:
                $model = new AnswerActivityUserStairsTotalNumber();
                break;
        }
        return $model;
    }


    /**
     * 获取操作记录model
     * @param pattern
     */
    public function getAnswerRecordModel($pattern)
    {
        switch ($pattern) {
            case 1:
                $model = new AnswerActivityUserAnswerRecord();
                break;
            case 2:
                $model = new AnswerActivityUserCorrectAnswerRecord();
                break;
            case 3:
                $model = new AnswerActivityUserStairsAnswerRecord();
                break;
        }
        return $model;
    }


    /**
     * 重置数据
     * @param act_id 活动id
     * @param start_time  只删除这个时间之前的数据
     */
    public function resetData($act_id, $start_time = null)
    {
        //删除所有的浏览数据
        AnswerActivityBrowseCount::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有的中奖信息
        AnswerActivityGift::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->update(['use_number' => 0]);
        //删除所有填写的邀请码
        AnswerActivityInvite::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有分享数据
        AnswerActivityShare::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();

        //删除所有用户选择单位信息
        AnswerActivityUnitUserNumber::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有答题记录
        AnswerActivityUserAnswerRecord::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有答题总记录
        AnswerActivityUserAnswerTotalNumber::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();

        //删除所有答题总记录
        AnswerActivityUserCorrectNumber::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();

        //删除所有答题总记录
        AnswerActivityUserCorrectAnswerRecord::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有答题总记录
        AnswerActivityUserCorrectTotalNumber::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();

        //删除所有用户中奖记录
        AnswerActivityUserGift::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有用户钥匙
        AnswerActivityUserPrize::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有用户钥匙记录
        AnswerActivityUserPrizeRecord::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();


        //删除所有爬楼梯形式总记录
        AnswerActivityUserStairsTotalNumber::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有爬楼梯形式总记录
        AnswerActivityUserStairsAnswerRecord::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();

        //删除所有用户选择的单位
        AnswerActivityUserUnit::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();
        //删除所有用户使用钥匙记录
        AnswerActivityUserUsePrizeRecord::where('act_id', $act_id)->where(function ($query) use ($start_time) {
            if ($start_time) {
                $query->where('create_time', '<', $start_time);
            }
        })->delete();

        return true;
    }
}
